package com.dt.platform.hr.controller;

import java.math.BigDecimal;
import java.util.*;

import com.dt.platform.domain.hr.*;
import com.dt.platform.domain.hr.meta.LearnTaskMeta;
import com.github.foxnic.sql.expr.ConditionExpr;
import org.github.foxnic.web.framework.web.SuperController;
import org.github.foxnic.web.session.SessionUser;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import com.github.foxnic.commons.collection.CollectorUtil;
import com.github.foxnic.dao.entity.ReferCause;
import com.github.foxnic.api.swagger.InDoc;
import org.github.foxnic.web.framework.sentinel.SentinelExceptionUtil;
import com.github.foxnic.api.swagger.ApiParamSupport;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.dt.platform.proxy.hr.PaperTaskServiceProxy;
import com.dt.platform.domain.hr.meta.PaperTaskVOMeta;
import com.github.foxnic.api.transter.Result;
import com.github.foxnic.dao.data.SaveMode;
import com.github.foxnic.dao.excel.ExcelWriter;
import com.github.foxnic.springboot.web.DownloadUtil;
import com.github.foxnic.dao.data.PagedList;
import java.util.Date;
import java.sql.Timestamp;
import com.github.foxnic.api.error.ErrorDesc;
import com.github.foxnic.commons.io.StreamUtil;
import java.util.Map;
import com.github.foxnic.dao.excel.ValidateResult;
import java.io.InputStream;
import com.dt.platform.domain.hr.meta.PaperTaskMeta;
import org.github.foxnic.web.domain.hrm.Employee;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiImplicitParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.dt.platform.hr.service.IPaperTaskService;
import com.github.foxnic.api.validate.annotations.NotNull;

/**
 * <p>
 * 考试任务接口控制器
 * </p>
 * @author 金杰 , maillank@qq.com
 * @since 2024-09-24 09:46:47
 */
@InDoc
@Api(tags = "考试任务")
@RestController("HrPaperTaskController")
public class PaperTaskController extends SuperController {

    @Autowired
    private IPaperTaskService paperTaskService;

    /**
     * 添加考试任务
     */
    @ApiOperation(value = "添加考试任务")
    @ApiImplicitParams({
		@ApiImplicitParam(name = PaperTaskVOMeta.ID, value = "主键", required = true, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.PAPER_ID, value = "试卷", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.PAPER_RELEASE_ID, value = "下发任务", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.NAME, value = "任务名称", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.STATUS, value = "任务状态", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.START_TIME, value = "开始时间", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.FINISH_TIME, value = "完成时间", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.USER_ID, value = "用户", required = true, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.UPDATE_BY, value = "修改人ID", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.PAPER_STATUS, value = "考试结果", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.SCORE, value = "考试得分", required = false, dataTypeClass = BigDecimal.class)
	})
    @ApiParamSupport(ignoreDBTreatyProperties = true, ignoreDefaultVoProperties = true, ignorePrimaryKey = true)
    @ApiOperationSupport(order = 1, author = "金杰 , maillank@qq.com")
    @SentinelResource(value = PaperTaskServiceProxy.INSERT, blockHandlerClass = { SentinelExceptionUtil.class }, blockHandler = SentinelExceptionUtil.HANDLER)
    @PostMapping(PaperTaskServiceProxy.INSERT)
    public Result insert(PaperTaskVO paperTaskVO) {
        Result result = paperTaskService.insert(paperTaskVO, false);
        return result;
    }

    /**
     * 删除考试任务
     */
    @ApiOperation(value = "删除考试任务")
    @ApiImplicitParams({
		@ApiImplicitParam(name = PaperTaskVOMeta.ID, value = "主键", required = true, dataTypeClass = String.class)
	})
    @ApiOperationSupport(order = 2, author = "金杰 , maillank@qq.com")
    @SentinelResource(value = PaperTaskServiceProxy.DELETE, blockHandlerClass = { SentinelExceptionUtil.class }, blockHandler = SentinelExceptionUtil.HANDLER)
    @PostMapping(PaperTaskServiceProxy.DELETE)
    public Result deleteById(String id) {
        this.validator().asserts(id).require("缺少id值");
        if (this.validator().failure()) {
            return this.validator().getFirstResult();
        }
        // 引用校验
        ReferCause cause = paperTaskService.hasRefers(id);
        // 判断是否可以删除
        this.validator().asserts(cause.hasRefer()).requireEqual("不允许删除当前记录：" + cause.message(), false);
        if (this.validator().failure()) {
            return this.validator().getFirstResult().messageLevel4Confirm();
        }
        Result result = paperTaskService.deleteByIdLogical(id);
        return result;
    }

    /**
     * 批量删除考试任务 <br>
     * 联合主键时，请自行调整实现
     */
    @ApiOperation(value = "批量删除考试任务")
    @ApiImplicitParams({
		@ApiImplicitParam(name = PaperTaskVOMeta.IDS, value = "主键清单", required = true, dataTypeClass = List.class, example = "[1,3,4]")
	})
    @ApiOperationSupport(order = 3, author = "金杰 , maillank@qq.com")
    @SentinelResource(value = PaperTaskServiceProxy.DELETE_BY_IDS, blockHandlerClass = { SentinelExceptionUtil.class }, blockHandler = SentinelExceptionUtil.HANDLER)
    @PostMapping(PaperTaskServiceProxy.DELETE_BY_IDS)
    public Result deleteByIds(List<String> ids) {
        // 参数校验
        this.validator().asserts(ids).require("缺少ids参数");
        if (this.validator().failure()) {
            return this.validator().getFirstResult();
        }
        // 查询引用
        Map<String, ReferCause> causeMap = paperTaskService.hasRefers(ids);
        // 收集可以删除的ID值
        List<String> canDeleteIds = new ArrayList<>();
        for (Map.Entry<String, ReferCause> e : causeMap.entrySet()) {
            if (!e.getValue().hasRefer()) {
                canDeleteIds.add(e.getKey());
            }
        }
        // 执行删除
        if (canDeleteIds.isEmpty()) {
            // 如果没有一行可以被删除
            return ErrorDesc.failure().message("无法删除您选中的数据行：").data(0).addErrors(CollectorUtil.collectArray(CollectorUtil.filter(causeMap.values(), (e) -> {
                return e.hasRefer();
            }), ReferCause::message, String.class)).messageLevel4Confirm();
        } else if (canDeleteIds.size() == ids.size()) {
            // 如果全部可以删除
            Result result = paperTaskService.deleteByIdsLogical(canDeleteIds);
            return result;
        } else if (canDeleteIds.size() > 0 && canDeleteIds.size() < ids.size()) {
            // 如果部分行可以删除
            Result result = paperTaskService.deleteByIdsLogical(canDeleteIds);
            if (result.failure()) {
                return result;
            } else {
                return ErrorDesc.success().message("已删除 " + canDeleteIds.size() + " 行，但另有 " + (ids.size() - canDeleteIds.size()) + " 行数据无法删除").data(canDeleteIds.size()).addErrors(CollectorUtil.collectArray(CollectorUtil.filter(causeMap.values(), (e) -> {
                    return e.hasRefer();
                }), ReferCause::message, String.class)).messageLevel4Confirm();
            }
        } else {
            // 理论上，这个分支不存在
            return ErrorDesc.success().message("数据删除未处理");
        }
    }

    /**
     * 更新考试任务
     */
    @ApiOperation(value = "更新考试任务")
    @ApiImplicitParams({
		@ApiImplicitParam(name = PaperTaskVOMeta.ID, value = "主键", required = true, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.PAPER_ID, value = "试卷", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.PAPER_RELEASE_ID, value = "下发任务", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.NAME, value = "任务名称", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.STATUS, value = "任务状态", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.START_TIME, value = "开始时间", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.FINISH_TIME, value = "完成时间", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.USER_ID, value = "用户", required = true, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.UPDATE_BY, value = "修改人ID", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.PAPER_STATUS, value = "考试结果", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.SCORE, value = "考试得分", required = false, dataTypeClass = BigDecimal.class)
	})
    @ApiParamSupport(ignoreDBTreatyProperties = true, ignoreDefaultVoProperties = true)
    @ApiOperationSupport(order = 4, author = "金杰 , maillank@qq.com", ignoreParameters = { PaperTaskVOMeta.PAGE_INDEX, PaperTaskVOMeta.PAGE_SIZE, PaperTaskVOMeta.SEARCH_FIELD, PaperTaskVOMeta.FUZZY_FIELD, PaperTaskVOMeta.SEARCH_VALUE, PaperTaskVOMeta.DIRTY_FIELDS, PaperTaskVOMeta.SORT_FIELD, PaperTaskVOMeta.SORT_TYPE, PaperTaskVOMeta.DATA_ORIGIN, PaperTaskVOMeta.QUERY_LOGIC, PaperTaskVOMeta.REQUEST_ACTION, PaperTaskVOMeta.IDS })
    @SentinelResource(value = PaperTaskServiceProxy.UPDATE, blockHandlerClass = { SentinelExceptionUtil.class }, blockHandler = SentinelExceptionUtil.HANDLER)
    @PostMapping(PaperTaskServiceProxy.UPDATE)
    public Result update(PaperTaskVO paperTaskVO) {
        Result result = paperTaskService.update(paperTaskVO, SaveMode.DIRTY_OR_NOT_NULL_FIELDS, false);
        return result;
    }

    /**
     * 保存考试任务
     */
    @ApiOperation(value = "保存考试任务")
    @ApiImplicitParams({
		@ApiImplicitParam(name = PaperTaskVOMeta.ID, value = "主键", required = true, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.PAPER_ID, value = "试卷", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.PAPER_RELEASE_ID, value = "下发任务", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.NAME, value = "任务名称", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.STATUS, value = "任务状态", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.START_TIME, value = "开始时间", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.FINISH_TIME, value = "完成时间", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.USER_ID, value = "用户", required = true, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.UPDATE_BY, value = "修改人ID", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.PAPER_STATUS, value = "考试结果", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.SCORE, value = "考试得分", required = false, dataTypeClass = BigDecimal.class)
	})
    @ApiParamSupport(ignoreDBTreatyProperties = true, ignoreDefaultVoProperties = true)
    @ApiOperationSupport(order = 5, ignoreParameters = { PaperTaskVOMeta.PAGE_INDEX, PaperTaskVOMeta.PAGE_SIZE, PaperTaskVOMeta.SEARCH_FIELD, PaperTaskVOMeta.FUZZY_FIELD, PaperTaskVOMeta.SEARCH_VALUE, PaperTaskVOMeta.DIRTY_FIELDS, PaperTaskVOMeta.SORT_FIELD, PaperTaskVOMeta.SORT_TYPE, PaperTaskVOMeta.DATA_ORIGIN, PaperTaskVOMeta.QUERY_LOGIC, PaperTaskVOMeta.REQUEST_ACTION, PaperTaskVOMeta.IDS })
    @SentinelResource(value = PaperTaskServiceProxy.SAVE, blockHandlerClass = { SentinelExceptionUtil.class }, blockHandler = SentinelExceptionUtil.HANDLER)
    @PostMapping(PaperTaskServiceProxy.SAVE)
    public Result save(PaperTaskVO paperTaskVO) {
        Result result = paperTaskService.save(paperTaskVO, SaveMode.DIRTY_OR_NOT_NULL_FIELDS, false);
        return result;
    }

    /**
     * 获取考试任务
     */
    @ApiOperation(value = "获取考试任务")
    @ApiImplicitParams({
		@ApiImplicitParam(name = PaperTaskVOMeta.ID, value = "主键", required = true, dataTypeClass = String.class, example = "1")
	})
    @ApiOperationSupport(order = 6, author = "金杰 , maillank@qq.com")
    @SentinelResource(value = PaperTaskServiceProxy.GET_BY_ID, blockHandlerClass = { SentinelExceptionUtil.class }, blockHandler = SentinelExceptionUtil.HANDLER)
    @PostMapping(PaperTaskServiceProxy.GET_BY_ID)
    public Result<PaperTask> getById(String id) {
        Result<PaperTask> result = new Result<>();
        PaperTask paperTask = paperTaskService.getById(id);
        // join 关联的对象

        paperTaskService.dao().fill(paperTask).with("user").with(PaperTaskMeta.PAPER_RELEASE).with(PaperTaskMeta.PAPER).execute();
        paperTaskService.dao().join(paperTask.getUser(), org.github.foxnic.web.domain.hrm.Person.class);
        result.success(true).data(paperTask);
        return result;
    }

    /**
     * 批量获取考试任务 <br>
     * 联合主键时，请自行调整实现
     */
    @ApiOperation(value = "批量获取考试任务")
    @ApiImplicitParams({
		@ApiImplicitParam(name = PaperTaskVOMeta.IDS, value = "主键清单", required = true, dataTypeClass = List.class, example = "[1,3,4]")
	})
    @ApiOperationSupport(order = 3, author = "金杰 , maillank@qq.com")
    @SentinelResource(value = PaperTaskServiceProxy.GET_BY_IDS, blockHandlerClass = { SentinelExceptionUtil.class }, blockHandler = SentinelExceptionUtil.HANDLER)
    @PostMapping(PaperTaskServiceProxy.GET_BY_IDS)
    public Result<List<PaperTask>> getByIds(List<String> ids) {
        Result<List<PaperTask>> result = new Result<>();
        List<PaperTask> list = paperTaskService.queryListByIds(ids);
        result.success(true).data(list);
        return result;
    }

    /**
     * 查询考试任务
     */
    @ApiOperation(value = "查询考试任务")
    @ApiImplicitParams({
		@ApiImplicitParam(name = PaperTaskVOMeta.ID, value = "主键", required = true, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.PAPER_ID, value = "试卷", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.PAPER_RELEASE_ID, value = "下发任务", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.NAME, value = "任务名称", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.STATUS, value = "任务状态", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.START_TIME, value = "开始时间", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.FINISH_TIME, value = "完成时间", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.USER_ID, value = "用户", required = true, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.UPDATE_BY, value = "修改人ID", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.PAPER_STATUS, value = "考试结果", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.SCORE, value = "考试得分", required = false, dataTypeClass = BigDecimal.class)
	})
    @ApiOperationSupport(order = 5, author = "金杰 , maillank@qq.com", ignoreParameters = { PaperTaskVOMeta.PAGE_INDEX, PaperTaskVOMeta.PAGE_SIZE })
    @SentinelResource(value = PaperTaskServiceProxy.QUERY_LIST, blockHandlerClass = { SentinelExceptionUtil.class }, blockHandler = SentinelExceptionUtil.HANDLER)
    @PostMapping(PaperTaskServiceProxy.QUERY_LIST)
    public Result<List<PaperTask>> queryList(PaperTaskVO sample) {
        Result<List<PaperTask>> result = new Result<>();
        List<PaperTask> list = paperTaskService.queryList(sample);
        result.success(true).data(list);
        return result;
    }

    /**
     * 分页查询考试任务
     */
    @ApiOperation(value = "分页查询考试任务")
    @ApiImplicitParams({
		@ApiImplicitParam(name = PaperTaskVOMeta.ID, value = "主键", required = true, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.PAPER_ID, value = "试卷", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.PAPER_RELEASE_ID, value = "下发任务", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.NAME, value = "任务名称", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.STATUS, value = "任务状态", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.START_TIME, value = "开始时间", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.FINISH_TIME, value = "完成时间", required = false, dataTypeClass = Date.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.USER_ID, value = "用户", required = true, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.UPDATE_BY, value = "修改人ID", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.PAPER_STATUS, value = "考试结果", required = false, dataTypeClass = String.class),
		@ApiImplicitParam(name = PaperTaskVOMeta.SCORE, value = "考试得分", required = false, dataTypeClass = BigDecimal.class)
	})
    @ApiOperationSupport(order = 8, author = "金杰 , maillank@qq.com")
    @SentinelResource(value = PaperTaskServiceProxy.QUERY_PAGED_LIST, blockHandlerClass = { SentinelExceptionUtil.class }, blockHandler = SentinelExceptionUtil.HANDLER)
    @PostMapping(PaperTaskServiceProxy.QUERY_PAGED_LIST)
    public Result<PagedList<PaperTask>> queryPagedList(PaperTaskVO sample) {
        Result<PagedList<PaperTask>> result = new Result<>();

        ConditionExpr expr=new ConditionExpr();
        expr.and("1=1");
        if("self".equals(sample.getQueryRole())){

            expr.and("user_id=?", SessionUser.getCurrent().getActivatedEmployeeId());
        }


        PagedList<PaperTask> list = paperTaskService.queryPagedList(sample,expr, sample.getPageSize(), sample.getPageIndex());
        // join 关联的对象


        paperTaskService.dao().fill(list).with("user").execute();
        List<Employee> userList = CollectorUtil.collectList(list, PaperTask::getUser);
        paperTaskService.dao().join(userList, org.github.foxnic.web.domain.hrm.Person.class);

        result.success(true).data(list);
        return result;
    }
}
